package com.xc.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.xc.common.Const;
import com.xc.common.ServerResponse;
import com.xc.dao.StockMapper;
import com.xc.pojo.Stock;
import com.xc.service.IStockService;
import com.xc.utils.HttpClientRequest;
import com.xc.utils.PropertiesUtil;
import com.xc.utils.redis.JsonUtil;
import com.xc.utils.stock.pinyin.GetPyByChinese;
import com.xc.utils.stock.sina.SinaStockApi;
import com.xc.vo.stock.MarketVO;
import com.xc.vo.stock.MarketVOResult;
import com.xc.vo.stock.StockListVO;
import com.xc.vo.stock.StockVO;
import com.xc.vo.stock.k.MinDataVO;
import com.xc.vo.stock.k.echarts.EchartsDataVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author mipha
 * @version 1.0
 * @date 2019/2/16 3:00 PM
 */
@Service("iStockService")
@Slf4j
public class StockServiceImpl implements IStockService {

    @Autowired
    StockMapper stockMapper;

    @Override
    public ServerResponse getMarket() {
        String market_url = PropertiesUtil.getProperty("sina.market.url");
        String result = null;
        try {
            result = HttpClientRequest.doGet(market_url);
        }catch (Exception e) {
            log.error("获取 大盘指数 出错 e = {}" , e);
        }
//        log.info("大盘指数数据 = {}" , result);

        //  先根据 ； 号分割
        String[] marketArray = result.split(";");

        List<MarketVO> marketVOS = Lists.newArrayList();
        for (int i = 0; i < marketArray.length; i++){
            String hqstr = marketArray[i];

            try {
                if(StringUtils.isNotBlank(hqstr)){
                    hqstr = hqstr.substring(hqstr.indexOf("\"") + 1, hqstr.lastIndexOf("\""));
//                    log.info("hqstr = {}" , hqstr);

                    MarketVO marketVO = new MarketVO();
                    String[] sh01_arr = hqstr.split(",");
                    marketVO.setName(sh01_arr[0]);
                    marketVO.setNowPrice(sh01_arr[1]);
                    marketVO.setIncrease(sh01_arr[2]);
                    marketVO.setIncreaseRate(sh01_arr[3]);

                    marketVOS.add(marketVO);
                }
            }catch (Exception e){
                log.error("转换大盘指数出错 str = {} ,  e = {}" , hqstr ,e);
            }
        }

        MarketVOResult marketVOResult = new MarketVOResult();
        marketVOResult.setMarket(marketVOS);

        return ServerResponse.createBySuccess(marketVOResult);
    }

    @Override
    public ServerResponse getStock(int pageNum , int pageSize , String keyWords) {

        // TODO: 2019/2/17 最好做每页条数限制 < 20 条
        //  开始分页
        PageHelper.startPage(pageNum, pageSize);

        //  查询所有显示的股票
        List<Stock> stockList = stockMapper.findStockListByKeyWords(keyWords, Const.StockShow.show);
//        log.info("查询到融资融券的股票 {} 条"  , stockList.size());

//        String test = JsonUtil.obj2String(stockList);
//        log.info("AAAAA test = {}" , test);

        List<StockListVO> stockListVOS = Lists.newArrayList();
        if(stockList.size() > 0){
            for (Stock stock : stockList){
                StockListVO stockListVO = SinaStockApi
                        .assembleStockListVO(SinaStockApi.getSinaStock(stock.getStockGid()));
                // 设置 code spell gid
                stockListVO.setCode(stock.getStockCode());
                stockListVO.setSpell(stock.getStockSpell());
                stockListVO.setGid(stock.getStockGid());
                stockListVOS.add(stockListVO);
            }
        }

        PageInfo pageInfo = new PageInfo(stockList);
        pageInfo.setList(stockListVOS);

        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse getSingleStock(String code) {
        if(StringUtils.isBlank(code)){
            return ServerResponse.createByErrorMsg("股票代码不能为空");
        }

        Stock stock = stockMapper.findStockByCode(code);
        if(stock == null){
            return ServerResponse.createByErrorMsg("股票不存在");
        }

        String gid = stock.getStockGid();
        String sinaResult = SinaStockApi.getSinaStock(gid);
        StockVO stockVO = SinaStockApi.assembleStockVO(sinaResult);

        stockVO.setId(stock.getId());
        //  获取 code spell gid
        stockVO.setCode(stock.getStockCode());
        stockVO.setSpell(stock.getStockSpell());
        stockVO.setGid(stock.getStockGid());

        //  获取k线图
        stockVO.setMinImg(PropertiesUtil.getProperty("sina.single.stock.min.url")+stock.getStockGid()+".jpg");
        stockVO.setDayImg(PropertiesUtil.getProperty("sina.single.stock.day.url")+stock.getStockGid()+".jpg");
        stockVO.setWeekImg(PropertiesUtil.getProperty("sina.single.stock.week.url")+stock.getStockGid()+".jpg");
        stockVO.setMonthImg(PropertiesUtil.getProperty("sina.single.stock.month.url")+stock.getStockGid()+".jpg");


        return ServerResponse.createBySuccess(stockVO);
    }

    @Override
    public ServerResponse getMinK(String code, Integer time, Integer ma, Integer size) {
        if(StringUtils.isBlank(code) ||
                time == null || ma == null || size == null){
            return ServerResponse.createByErrorMsg("参数不能为空");
        }

        Stock stock = stockMapper.findStockByCode(code);
        if(stock == null){
            return ServerResponse.createByErrorMsg("股票不存在");
        }

        ServerResponse<MinDataVO> serverResponse = SinaStockApi.getStockMinK(stock,time,ma,size);
        return serverResponse;
    }

    @Override
    public ServerResponse getMinK_Echarts(String code, Integer time, Integer ma, Integer size) {
        if(StringUtils.isBlank(code) ||
                time == null || ma == null || size == null){
            return ServerResponse.createByErrorMsg("参数不能为空");
        }

        Stock stock = stockMapper.findStockByCode(code);
        if(stock == null){
            return ServerResponse.createByErrorMsg("股票不存在");
        }

        ServerResponse<MinDataVO> serverResponse = SinaStockApi.getStockMinK(stock,time,ma,size);

        MinDataVO minDataVO = serverResponse.getData();

        //  minDataVO To echartsDataVO
        EchartsDataVO echartsDataVO = SinaStockApi.assembleEchartsDataVO(minDataVO);

        return ServerResponse.createBySuccess(echartsDataVO);
    }

    @Override
    public ServerResponse<Stock> findStockByName(String name) {
        return ServerResponse.createBySuccess(stockMapper.findStockByName(name));
    }

    @Override
    public ServerResponse<Stock> findStockByCode(String code) {
        return ServerResponse.createBySuccess(stockMapper.findStockByCode(code));
    }

    @Override
    public ServerResponse<Stock> findStockById(Integer stockId) {
        return ServerResponse.createBySuccess(stockMapper.selectByPrimaryKey(stockId));
    }

    @Override
    public ServerResponse<PageInfo> listByAdmin(Integer showState, Integer lockState, String code, String name, int pageNum, int pageSize, HttpServletRequest request) {

        PageHelper.startPage(pageNum,pageSize);

        List<Stock> stockList = stockMapper.listByAdmin(showState,lockState,code,name);

        PageInfo pageInfo = new PageInfo(stockList);

        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse updateLock(Integer stockId) {

        Stock stock = stockMapper.selectByPrimaryKey(stockId);
        if(stock == null){
            return ServerResponse.createByErrorMsg("股票不存在");
        }

        if(stock.getIsLock() == Const.StockLock.lock){
            stock.setIsLock(Const.StockLock.no_lock);
        }else{
            stock.setIsLock(Const.StockLock.lock);
        }

        int updateCount = stockMapper.updateByPrimaryKeySelective(stock);
        if(updateCount > 0){
            return ServerResponse.createBySuccessMsg("修改成功");
        }else{
            return ServerResponse.createByErrorMsg("修改失败");
        }
    }

    @Override
    public ServerResponse updateShow(Integer stockId) {
        Stock stock = stockMapper.selectByPrimaryKey(stockId);
        if(stock == null){
            return ServerResponse.createByErrorMsg("股票不存在");
        }

        if(stock.getIsShow() == Const.StockShow.show){
            stock.setIsShow(Const.StockShow.no_show);
        }else{
            stock.setIsShow(Const.StockShow.show);
        }

        int updateCount = stockMapper.updateByPrimaryKeySelective(stock);
        if(updateCount > 0){
            return ServerResponse.createBySuccessMsg("修改成功");
        }else{
            return ServerResponse.createByErrorMsg("修改失败");
        }
    }

    @Override
    public ServerResponse addStock(String stockName, String stockCode, String stockType, Integer isLock, Integer isShow) {
        if(StringUtils.isBlank(stockName) || StringUtils.isBlank(stockCode)
                || StringUtils.isBlank(stockType) || isLock == null || isShow == null){
            return ServerResponse.createByErrorMsg("参数不能为空");
        }

        Stock cstock = findStockByCode(stockCode).getData();
        if(cstock != null){
            return ServerResponse.createByErrorMsg("股票代码已存在");
        }

        Stock nstock = findStockByName(stockName).getData();
        if(nstock != null){
            return ServerResponse.createByErrorMsg("股票名已存在");
        }

        Stock stock = new Stock();
        stock.setStockName(stockName);
        stock.setStockCode(stockCode);
        stock.setStockSpell(GetPyByChinese.converterToFirstSpell(stockName));
        stock.setStockType(stockType);
        stock.setStockGid(stockType + stockCode);
        stock.setIsLock(isLock);
        stock.setIsShow(isShow);
        stock.setAddTime(new Date());
        int insertCount = stockMapper.insert(stock);
        if(insertCount > 0){
            return ServerResponse.createBySuccessMsg("添加股票成功");
        }else{
            return ServerResponse.createByErrorMsg("添加股票失败");
        }
    }

    @Override
    public int CountStockNum() {
        return stockMapper.CountStockNum();
    }

    @Override
    public int CountShowNum(Integer showState) {
        return stockMapper.CountShowNum(showState);
    }

    @Override
    public int CountUnLockNum(Integer lockState) {
        return stockMapper.CountUnLockNum(lockState);
    }


}


